package top.mengchaob.gitManage.service;

import org.eclipse.jgit.api.errors.GitAPIException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import top.mengchaob.deploy.api.DeployServiceI;
import top.mengchaob.exception.RelationBranchException;
import top.mengchaob.exception.RemoteBranchNotExistException;
import top.mengchaob.fileserver.netty.jpa.FileRepository;
import top.mengchaob.fileserver.netty.table.FileDo;
import top.mengchaob.gitManage.api.GitManageServiceI;
import top.mengchaob.gitManage.jpa.GitFileRepository;
import top.mengchaob.gitManage.table.GitFileDo;
import top.mengchaob.gitManage.util.GitUtil;
import top.mengchaob.maven.MvnUtil;
import top.mengchaob.util.PropUtil;
import top.mengchaob.util.UtilTimeFormatter;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @title：
 * @author: mengchaob
 * @date: 2021年06月03日 14:21
 * @description:
 */
@Service
public class GitManageService implements GitManageServiceI {
    private static Logger logger = LoggerFactory.getLogger(GitManageService.class);
    @Autowired
    @Qualifier("gitUtil")
    GitUtil gitUtil;
    @Autowired
    @Qualifier("mvnUtil")
    MvnUtil mvnUtil;
    @Autowired
    FileRepository fileRepository;
    @Autowired
    GitFileRepository gitFileRepository;
    @Override
    public void packageBranch(String branchNames) throws RelationBranchException, RemoteBranchNotExistException {
        String[] branchNameArr = branchNames.split(",");
        for (int p = 0; p < branchNameArr.length; p++) {
            String branchName = branchNameArr[p];
            //1.检出分支
            gitUtil.checkOutBranch(branchName);
            //2.pull最新代码
            gitUtil.pullBranch(branchName);
            //3.打包
            mvnUtil.packWar(branchName);
            //4.删除文件信息
            this.gitFileinfoDelete(branchName);
            //5.文件信息入库
            this.gitFileinfoSave(branchName);
        }

    }

    private void gitFileinfoDelete(String branchName){
        List<FileDo> list = gitFileRepository.getGitFileDoByBranchName(branchName);
        StringBuffer stringBuffer = new StringBuffer();
        list.stream().forEach(fileDo->{
            stringBuffer.append(",").append(fileDo.getFileId());
                });
        String ids = stringBuffer.toString();
        String fileString = PropUtil.getV("baseUrl")+File.separator+branchName;
        File[] files = new File(fileString).listFiles();
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            String fileName = file.getName().substring(0,file.getName().lastIndexOf("."));
            if(file.isFile() && ids.contains(fileName)){
                file.delete();
                fileRepository.deleteById(fileName);
                ids = ids.replace(","+fileName,"");
            }
        }
        String[] dirtyId = ids.split(",");
        for (int i = 1; i < dirtyId.length; i++) {
            fileRepository.deleteById(dirtyId[i]);
        }
    }

    private void gitFileinfoSave(String branchName){
        String fileString = PropUtil.getV("baseUrl")+File.separator+branchName;
        File[] files = new File(fileString).listFiles();
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if(file.isFile()){
                //插入文件信息
                String uuid = UUID.randomUUID().toString();
                FileDo fileDo = new FileDo();
                fileDo.setFileId(uuid);
                fileDo.setFileName(file.getName());
                String rootPath = file.getParent();
                File newFile = new File(rootPath + File.separator + uuid+file.getName().substring(file.getName().lastIndexOf(".")));
                if(file.renameTo(newFile)){
                    logger.debug(fileDo.getFileName()+"修改文件名成功，修改后为"+newFile.getName());
                }else {
                    logger.error(fileDo.getFileName()+"修改文件名失败");
                }
                fileDo.setLbCode(branchName);
                fileDo.setType(2+"");
                fileDo.setCreateTime(UtilTimeFormatter.getTimeToYMDHMS(new Date().getTime()));
                fileRepository.save(fileDo);
                //保存git分支同文件关系
                GitFileDo gitFileDo = new GitFileDo();
                gitFileDo.setBranchName(branchName);
                gitFileDo.setFileId(fileDo.getFileId());
                gitFileDo.setId(uuid);
                gitFileRepository.save(gitFileDo);
            }
        }
    }

    @Override
    public void checkOutBranch(String branchName) throws RelationBranchException, RemoteBranchNotExistException {
        gitUtil.checkOutBranch(branchName);
    }

    @Override
    public void pullBranch(String branchName) {
        gitUtil.pullBranch(branchName);
    }

    @Override
    public String getCurrentBranch() {
        return gitUtil.currentBranchName();
    }

    @Override
    public void cleanBranch(String branchName) {
        mvnUtil.cleanByBranchName(PropUtil.getV("maven.localOutDir")+ File.separator+branchName);
    }

    @Override
    public List getGitFileByBranch(String branchName) {
        List list = gitFileRepository.getGitFileDoByBranchName(branchName);
        return list;
    }

    @Override
    public void gitClone() throws GitAPIException {
        gitUtil.gitcloneUrl(PropUtil.getByKey("git.url"),PropUtil.getByKey("git.workSpace"));
    }
}
